<template>
  <el-dialog
    :visible.sync="visible"
    :title="$t('updatePassword.title')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :append-to-body="true"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()"
      label-width="120px"
    >
      <el-form-item :label="$t('updatePassword.username')">
        <span>{{ $store.state.user.name }}</span>
      </el-form-item>
      <el-form-item prop="password" :label="$t('updatePassword.password')">
        <el-input
          v-model="dataForm.password"
          type="password"
          :placeholder="$t('updatePassword.password')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="newPassword" :label="$t('updatePassword.newPassword')">
        <el-input
          v-model="dataForm.newPassword"
          type="password"
          :placeholder="$t('updatePassword.newPassword')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword" :label="$t('updatePassword.confirmPassword')">
        <el-input
          v-model="dataForm.confirmPassword"
          type="password"
          :placeholder="$t('updatePassword.confirmPassword')"
        ></el-input>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from "lodash/debounce";
import { clearLoginInfo } from "@/utils";
import { decryptECB, encryptECB } from "@/utils/encryptAndDecryptUtils";
import {encrypt,decrypt} from "@/utils/sm4Utils";
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        password: "",
        newPassword: "",
        confirmPassword: "",
      },
    };
  },
  computed: {
    dataRule() {
      var validateNewPassword = (rule, value, callback) => {
        const lengthValid = this.dataForm.newPassword.length >= 8;
        const hasNumber = /[0-9]/.test(this.dataForm.newPassword);
        const hasLetter = /[a-zA-Z]/.test(this.dataForm.newPassword);
        const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(this.dataForm.newPassword);
        const typesCount = [hasNumber, hasLetter, hasSpecialChar].filter(Boolean).length;
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t("validate.required")));
        }
        if (!lengthValid) {
          return callback(new Error("密码长度必须至少为8位"));
          // this.errorMessage = '密码长度必须至少为8位';
        }
        if (typesCount < 3) {
          return callback(new Error("密码必须由数字、字母和特殊字符3种组成"));
          // this.errorMessage = '密码必须由数字、字母或特殊字符中的3种组成';
        }
        callback();
      };
      var validateConfirmPassword = (rule, value, callback) => {
        if (this.dataForm.newPassword !== value) {
          return callback(new Error(this.$t("updatePassword.validate.confirmPassword")));
        }
        callback();
      };
      return {
        password: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
        ],
        newPassword: [{ validator: validateNewPassword, trigger: "blur" }],
        confirmPassword: [
          { required: true, message: this.$t("validate.required"), trigger: "blur" },
          { validator: validateConfirmPassword, trigger: "blur" },
        ],
      };
    },
  },
  methods: {
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
      });
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate(async (valid) => {
          if (!valid) {
            return false;
          }
          console.log("dataForm", this.dataForm);
          let params = await encryptECB(JSON.stringify(this.dataForm));
           let xSecret = await encrypt(params)
          this.$http
            .post("/sys/user/password", params, {
              headers: {
                "x-secret":xSecret,
                "Content-Type": "application/json",
              },
            })
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  clearLoginInfo();
                  this.$router.replace({ name: "login" });
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>
